package cn.wolfcode.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @ClassName AuthGlobalFilter
 * @Author VCR
 * @Date 2021/12/23 21:58
 * @Version 1.0
 */
@Component
public class AuthGlobalFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 前置逻辑
        // 获取token
        String token = exchange.getRequest().getQueryParams().getFirst("token");
        String av = exchange.getRequest().getQueryParams().getFirst("av");

        if (StringUtils.isEmpty(token) || "666".equals(token)) {
            // 拦截并且给他响应一个401状态码(HttpStatus.UNAUTHORIZED即为401)
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }
}
